package br.com.fiap.fiappizzas;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import br.com.fiap.fiappizzas.dao.ClientDAO;
import br.com.fiap.fiappizzas.db.entities.Address;
import br.com.fiap.fiappizzas.db.entities.Client;

public class CadastroClienteActivity extends Activity implements OnClickListener {

	private ClientDAO clientDAO;
	private Context context = this;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cadastro_cliente);

		clientDAO = new ClientDAO(this);
		
		Button b = (Button) findViewById(R.id.bt_cadastrar);
		b.setOnClickListener(this);
			
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.fiap_pizzas, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		
		final Client client = getClientFromView();
		
		clientDAO.insert(client);
		
		Intent intent = new Intent(context, FiapPizzasActivity.class);
		intent.putExtra("phoneInsertedClient", client.getPhone());
		
		startActivity(intent);
		
	}

	private Client getClientFromView() {
		final Client client = new Client();
		
		client.setName(((EditText)findViewById(R.id.field_name)).getText().toString());
		client.setPhone(((EditText)findViewById(R.id.field_phone)).getText().toString());
		
		final Address address = getAddressFromView();
		
		client.setAddress(address);
		return client;
	}

	private Address getAddressFromView() {
		final Address address = new Address();
		address.setStreet(((EditText)findViewById(R.id.field_street)).getText().toString());
		address.setNumber(Integer.valueOf(((EditText)findViewById(R.id.field_number)).getText().toString()));
		address.setNeighborhood(((EditText)findViewById(R.id.field_neighborhood)).getText().toString());
		address.setCity(((EditText)findViewById(R.id.field_city)).getText().toString());
		address.setState(((EditText)findViewById(R.id.field_state)).getText().toString());
		return address;
	}

}
